import axios from 'axios';

import NProgress from 'nprogress';

import { formatJsonToUrlParams, instanceObject } from './format';

let baseURL = '/api';

const AxiosInstance = axios.create({
  baseURL,
  timeout: 5000,
});
//请求拦截器
AxiosInstance.interceptors.request.use(
  (config) => {
    // const token = localStorage.getItem('token');
    // if (token) {
    //   config.headers['Authorization'] = token;
    // }
    NProgress.start();
    return config;
  },
  (error) => {
    NProgress.done();
    return Promise.reject(error);
  }
);
AxiosInstance.interceptors.response.use(
  (response: any) => {
    const res = response.data;
    if (response.status !== 200) {
      return Promise.reject(new Error(res.error || '请求失败'));
    } else {
      if (res.code == 200) {
        NProgress.done();
        return response;
      } else {
        alert(res.error);
      }
    }
  },
  (error) => {
    NProgress.done();
    return Promise.reject(error || '请求失败');
  }
);
const service = {
  get<T = any>(url: string, data?: object): Promise<T> {
    return AxiosInstance.get(url, { params: data });
  },
  post<T = any>(url: string, data?: object): Promise<T> {
    return AxiosInstance.post(url, data);
  },
  put<T = any>(url: string, data?: object): Promise<T> {
    return AxiosInstance.put(url, data);
  },
  delete<T = any>(url: string, data?: object): Promise<T> {
    return AxiosInstance.delete(url, data);
  },
  upload: (url: string, file: FormData | File) =>
    AxiosInstance.post(url, file, {
      headers: { 'Content-Type': 'multipart/form-data' },
    }),
  download: (url: string, data: instanceObject) => {
    window.location.href = `${baseURL}/${url}?${formatJsonToUrlParams(data)}`;
  },
};
export default service;
